package com.jubao.ejb.business.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ejb.Stateless;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.jboss.ejb3.annotation.LocalBinding;
import org.jboss.ejb3.annotation.RemoteBinding;

import com.jubao.ejb.business.Business;
import com.jubao.ejb.business.DataImportBusinessLocal;
import com.jubao.ejb.business.DataImportBusinessRemote;
import com.jubao.ejb.business.util.BusinessConstant;
import com.jubao.ejb.entity.Brand;
import com.jubao.ejb.entity.Category;
import com.jubao.ejb.entity.Coupon;
import com.jubao.ejb.entity.CouponItem;
import com.jubao.ejb.entity.GeneRelation;
import com.jubao.ejb.entity.Product;
import com.jubao.ejb.entity.ProductPrice;
import com.jubao.ejb.entity.Store;
import com.jubao.ejb.entity.StoreTransaction;
import com.jubao.ejb.entity.User;
import com.jubao.ejb.entity.Website;

@Stateless
@LocalBinding(jndiBinding = BusinessConstant.DataImportBusinessLocalJndiName)
@RemoteBinding(jndiBinding = BusinessConstant.DataImportBusinessRemoteJndiName)
public class DataImportBusinessImpl extends Business implements DataImportBusinessLocal, DataImportBusinessRemote {
	static Logger logger = Logger.getLogger(DataImportBusinessImpl.class);

	public void importData(Document document) throws DocumentException, InterruptedException {
		treeWalk(document);
	}

	/* (non-Javadoc)
	 * @see com.fengniu.ejb.business.IDataImportBusiness#importData(java.lang.String)
	 */
	public void importData(String xml) throws DocumentException, InterruptedException {
		Document document = DocumentHelper.parseText(xml);
		importData(document);
	}

	private void treeWalk(Document document) throws InterruptedException {
		treeWalk(document.getRootElement());
	}

	private void treeWalk(Element element) throws InterruptedException {
		for (int i = 0, size = element.nodeCount(); i < size; i++) {
			Node node = element.node(i);
			if (node instanceof Element) {
				if (importBrand((Element) node, i)) {
				} else if (importCategory((Element) node, i)) {
				} else if (importBrand2Category((Element) node, i)) {
				} else if (importProduct((Element) node, i)) {
				} else if (importProduct2Category((Element) node, i)) {
				} else if (importProduct2Brand((Element) node, i)) {
				} else if (importStore((Element) node, i)) {
				} else if (importStore2Category((Element) node, i)) {
				} else if (importStore2ProductPrice((Element) node, i)) {
				} else if (importCoupon((Element) node, i)) {
				} else if (importCouponItem((Element) node, i)) {
				} else if (importStoreTransaction((Element) node, i)) {
				} else if (importWebsite((Element) node, i)) {
				} else if (importWebsite2Category((Element) node, i)) {
				} else if (importUser((Element) node, i)) {
				} else if (importUser2Category((Element) node, i)) {
				} else if (importUser2Store((Element) node, i)) {
				} else if (importUser2Product((Element) node, i)) {
				}
				// TODO: check whether child element should be treeWalk
				// for example rss.xml only need to walk to Item will be enough,
				// not
				// need to walk into children of Item
				treeWalk((Element) node);
			} else {
				// do something....
			}
		}
	}

	private boolean importBrand(final Element element, final int sequence) {
		if (!element.getName().equals("Brand"))
			return false;

		String brandId = element.attributeValue("id");
		Brand pg = brandDao.find(brandId);
		if (pg == null) {
			pg = new Brand();
			pg.setId(brandId);
		}
		pg.setName(element.attributeValue("name"));
		pg.setFullName(element.attributeValue("fullName"));
		pg.setSmallImage(element.attributeValue("smallImage"));

		brandDao.save(pg);
		return true;
	}

	/**
		 * Sample xml data:- <HonguoziCategory> <!-- Don't isediterof sysId in this
		 * file <ProductGroup sysId="s2020000001000" name="经营范围" /> --> <Category
		 * sysId="s2010000001000" name="各个地区"> <Category sysId="s00001" name="guang
		 * dong" /> <Category sysId="s00002" name="bei jing" /> </Category>
		 * <Category sysId="s2020000001000" name="经营范围" /> </HonguoziCategory>
		 * 
		 * @param element
		 * @return
		 */
	private boolean importCategory(final Element element, final int sequence) {
		if (!element.getName().equals("Category"))
			return false;

		String categoryId = element.attributeValue("id");
		Category pg = categoryDao.find(categoryId);
		if (pg == null) {
			pg = new Category();
			pg.setId(categoryId);
		}
		pg.setName(element.attributeValue("name"));
		pg.setFullName(element.attributeValue("fullName"));
		pg.setSmallImage(element.attributeValue("smallImage"));

		Element parent = element.getParent();
		if (parent != null && parent.attributeValue("id") != null) {
			String parentId = parent.attributeValue("id");
			Category pcat = categoryDao.find(parentId);
			if (pcat != null) {
				pg.setPrimaryParent(pcat);
			}
		}
		categoryDao.save(pg);
		return true;
	}

	private boolean importBrand2Category(final Element element, final int sequence) {
		if (!element.getName().equals("Brand2Category"))
			return false;

		String brandId = element.attributeValue("brandId");
		String relationName = element.attributeValue("relationName");
		String categoryId = element.attributeValue("categoryId");

		Integer relationId = BusinessConstant.RelationID.valueOf(BusinessConstant.RelationID.class, relationName)
				.getId();

		Brand brand = brandDao.find(brandId);
		Category category = categoryDao.find(categoryId);
		if (brand != null && category != null) {
			GeneRelation gr = geneRelationDao.find(brand.getSysId(), relationId, category.getSysId());
			if (gr == null) {
				gr = new GeneRelation();
				gr.setEntity(brand);
				gr.setRelationId(relationId);
				gr.setEntity2(category);
				geneRelationDao.save(gr);
			}
		} else {
			if (brand == null)
				logger.info("Not Found Brand id=[" + brandId + "]");
			if (category == null)
				logger.info("Not Found Category id=[" + categoryId + "]");
		}
		return true;
	}

	private boolean importProduct(final Element element, final int sequence) {
		if (!element.getName().equals("Product"))
			return false;

		String productId = element.attributeValue("id");
		String name = element.attributeValue("name");
		String fullName = element.attributeValue("fullName");

		int rank = 0;
		try {
			rank = element.attributeValue("rank") == null ? 0 : Integer.parseInt(element.attributeValue("rank"));
		} catch (NumberFormatException e) {
			rank = 0;
		}
		String smallImage = element.attributeValue("smallImage");
		String mediumImage = element.attributeValue("mediumImage");
		String largeImage = element.attributeValue("largeImage");

		String shortDesc = element.elementText("shortDesc");
		String longDesc = element.elementText("longDesc");

		String brandId = element.attributeValue("brandId");
		String primaryCategoryId = element.attributeValue("primaryCategoryId");

		String supplierId = element.attributeValue("supplierId");

		Product product = super.productDao.find(productId);
		if (product == null) {
			product = new Product();
			product.setId(productId);
		}

		if (supplierId != null) {
			User supplier = userDao.find(supplierId);
			if (supplier != null) {
				product.setSupplier(supplier);
			}
		}

		if (name != null && !name.trim().equals(""))
			product.setName(name);
		if (fullName != null && !fullName.trim().equals(""))
			product.setFullName(fullName);

		product.setRank(rank);
		if (smallImage != null && !smallImage.trim().equals(""))
			product.setSmallImage(smallImage);
		if (mediumImage != null && !mediumImage.trim().equals(""))
			product.setMediumImage(mediumImage);
		if (largeImage != null && !largeImage.trim().equals(""))
			product.setLargeImage(largeImage);

		if (shortDesc != null && !shortDesc.trim().equals(""))
			product.setShortDesc(shortDesc);
		if (longDesc != null && !longDesc.trim().equals(""))
			product.setLongDesc(longDesc);

		if (brandId != null && !brandId.trim().equals("")) {
			Brand brand = brandDao.find(brandId);
			if (brand != null)
				product.setBrand(brand);
		}
		if (primaryCategoryId != null && !primaryCategoryId.trim().equals("")) {
			Category primaryCategory = categoryDao.find(primaryCategoryId);
			if (primaryCategory != null)
				product.setPrimaryCategory(primaryCategory);
		}
		productDao.save(product);
		return true;
	}

	private boolean importProduct2Category(final Element element, final int sequence) {
		if (!element.getName().equals("Product2Category"))
			return false;

		String productId = element.attributeValue("productId");
		String relationName = element.attributeValue("relationName");
		String categoryId = element.attributeValue("categoryId");

		Integer relationId = BusinessConstant.RelationID.valueOf(BusinessConstant.RelationID.class, relationName)
				.getId();

		Product product = productDao.find(productId);
		Category category = categoryDao.find(categoryId);
		if (product != null && category != null) {
			GeneRelation gr = geneRelationDao.find(product.getSysId(), relationId, category.getSysId());
			if (gr == null) {
				gr = new GeneRelation();
				gr.setEntity(product);
				gr.setRelationId(relationId);
				gr.setEntity2(category);
				geneRelationDao.save(gr);
			}
		} else {
			if (product == null)
				logger.info("Not Found Product id=[" + productId + "]");
			if (category == null)
				logger.info("Not Found Category id=[" + categoryId + "]");
		}
		return true;
	}

	private boolean importProduct2Brand(final Element element, final int sequence) {
		if (!element.getName().equals("Product2Brand"))
			return false;

		String productId = element.attributeValue("productId");
		String relationName = element.attributeValue("relationName");
		String brandId = element.attributeValue("brandId");

		Integer relationId = BusinessConstant.RelationID.valueOf(BusinessConstant.RelationID.class, relationName)
				.getId();

		Product product = productDao.find(productId);
		Brand brand = brandDao.find(brandId);
		if (product != null && brand != null) {
			GeneRelation gr = geneRelationDao.find(product.getSysId(), relationId, brand.getSysId());
			if (gr == null) {
				gr = new GeneRelation();
				gr.setEntity(product);
				gr.setRelationId(relationId);
				gr.setEntity2(brand);
				geneRelationDao.save(gr);
			}
		} else {
			if (product == null)
				logger.info("Not Found Product id=[" + productId + "]");
			if (brand == null)
				logger.info("Not Found Brand id=[" + brandId + "]");
		}
		return true;
	}

	private boolean importStore(final Element element, final int sequence) {
		if (!element.getName().equals("Store"))
			return false;

		String storeId = element.attributeValue("id");
		String name = element.attributeValue("name");
		String status = element.attributeValue("status");
		Integer statusId = -1;
		if (status != null) {
			statusId = BusinessConstant.RelationID.valueOf(BusinessConstant.Status.class, status).getId();
		}

		int rank = 0;
		try {
			rank = element.attributeValue("rank") == null ? 0 : Integer.parseInt(element.attributeValue("rank"));
		} catch (NumberFormatException e) {
			rank = 0;
		}
		String shortDesc = element.elementText("shortDesc");
		String longDesc = element.elementText("longDesc");

		String primaryAreaCategoryId = element.attributeValue("primaryAreaCategoryId");
		String primaryBusinessCategoryId = element.attributeValue("primaryBusinessCategoryId");

		Store store = storeDao.find(storeId);
		if (store == null) {
			store = new Store();
			store.setId(storeId);
		}

		if (name != null && !name.trim().equals(""))
			store.setName(name);
		store.setStatus(statusId);
		store.setRank(rank);
		if (shortDesc != null && !shortDesc.trim().equals(""))
			store.setShortDesc(shortDesc);
		if (longDesc != null && !longDesc.trim().equals(""))
			store.setLongDesc(longDesc);

		if (primaryAreaCategoryId != null && !primaryAreaCategoryId.trim().equals("")) {
			Category cat = categoryDao.find(primaryAreaCategoryId);
			if (cat != null)
				store.setPrimaryAreaCategory(cat);
		}

		if (primaryBusinessCategoryId != null && !primaryBusinessCategoryId.trim().equals("")) {
			Category cat = categoryDao.find(primaryBusinessCategoryId);
			if (cat != null)
				store.setPrimaryBusinessCategory(cat);
		}

		storeDao.save(store);
		return true;
	}

	private boolean importStore2Category(final Element element, final int sequence) {
		if (!element.getName().equals("Store2Category"))
			return false;

		String storeId = element.attributeValue("storeId");
		String relationName = element.attributeValue("relationName");
		String categoryId = element.attributeValue("categoryId");

		Integer relationId = BusinessConstant.RelationID.valueOf(BusinessConstant.RelationID.class, relationName)
				.getId();

		Store store = storeDao.find(storeId);
		Category category = categoryDao.find(categoryId);
		if (store != null && category != null) {
			GeneRelation gr = geneRelationDao.find(store.getSysId(), relationId, category.getSysId());
			if (gr == null) {
				gr = new GeneRelation();
				gr.setEntity(store);
				gr.setRelationId(relationId);
				gr.setEntity2(category);
				geneRelationDao.save(gr);
			}
		} else {
			if (store == null)
				logger.info("Not Found Store id=[" + storeId + "]");
			if (category == null)
				logger.info("Not Found Category id=[" + categoryId + "]");
		}

		return true;
	}

	private boolean importWebsite(final Element element, final int sequence) {
		if (!element.getName().equals("Website"))
			return false;

		String storeId = element.attributeValue("id");
		String name = element.attributeValue("name");
		String status = element.attributeValue("status");

		String searchUrl = element.attributeValue("searchUrl");
		String rssUrl = element.attributeValue("rssUrl");

		Integer statusId = -1;
		if (status != null) {
			statusId = BusinessConstant.RelationID.valueOf(BusinessConstant.Status.class, status).getId();
		}

		int rank = 0;
		try {
			rank = element.attributeValue("rank") == null ? 0 : Integer.parseInt(element.attributeValue("rank"));
		} catch (NumberFormatException e) {
			rank = 0;
		}
		String shortDesc = element.elementText("shortDesc");

		String primaryAreaCategoryId = element.attributeValue("primaryAreaCategoryId");
		String primaryWebsiteCategoryId = element.attributeValue("primaryWebsiteCategoryId");

		Website website = websiteDao.find(storeId);
		if (website == null) {
			website = new Website();
			website.setId(storeId);
		}

		if (name != null && !name.trim().equals(""))
			website.setName(name);
		website.setStatus(statusId);
		website.setRank(rank);

		if (shortDesc != null && !shortDesc.trim().equals(""))
			website.setShortDesc(shortDesc);

		if (searchUrl != null && !searchUrl.trim().equals(""))
			website.setSearchUrl(searchUrl);

		if (rssUrl != null && !rssUrl.trim().equals(""))
			website.setRssUrl(rssUrl);

		if (primaryAreaCategoryId != null && !primaryAreaCategoryId.trim().equals("")) {
			Category cat = categoryDao.find(primaryAreaCategoryId);
			if (cat != null)
				website.setPrimaryAreaCategory(cat);
		}

		if (primaryWebsiteCategoryId != null && !primaryWebsiteCategoryId.trim().equals("")) {
			Category cat = categoryDao.find(primaryWebsiteCategoryId);
			if (cat != null)
				website.setPrimaryWebsiteCategory(cat);
		}

		websiteDao.save(website);
		return true;
	}

	private boolean importWebsite2Category(final Element element, final int sequence) {
		if (!element.getName().equals("Website2Category"))
			return false;

		String websiteId = element.attributeValue("websiteId");
		String relationName = element.attributeValue("relationName");
		String categoryId = element.attributeValue("categoryId");

		Integer relationId = BusinessConstant.RelationID.valueOf(BusinessConstant.RelationID.class, relationName)
				.getId();

		Website website = websiteDao.find(websiteId);
		Category category = categoryDao.find(categoryId);
		if (website != null && category != null) {
			GeneRelation gr = geneRelationDao.find(website.getSysId(), relationId, category.getSysId());
			if (gr == null) {
				gr = new GeneRelation();
				gr.setEntity(website);
				gr.setRelationId(relationId);
				gr.setEntity2(category);
				geneRelationDao.save(gr);
			}
		} else {
			if (website == null)
				logger.info("Not Found Website id=[" + websiteId + "]");
			if (category == null)
				logger.info("Not Found Category id=[" + categoryId + "]");
		}

		return true;
	}

	private boolean importStore2ProductPrice(final Element element, final int sequence) {
		if (!element.getName().equals("Store2Product"))
			return false;

		String storeId = element.attributeValue("storeId");
		String relationName = element.attributeValue("relationName");
		String productId = element.attributeValue("productId");
		String listPrice = element.attributeValue("listPrice");
		String memberPrice = element.attributeValue("memberPrice");

		Integer relationId = BusinessConstant.RelationID.valueOf(BusinessConstant.RelationID.class, relationName)
				.getId();
		Store store = storeDao.find(storeId);
		Product product = productDao.find(productId);
		if (store != null && product != null) {
			ProductPrice gr = productPriceDao.find(store.getSysId(), relationId, product.getSysId());
			if (gr == null) {
				gr = new ProductPrice();
				gr.setStore(store);
				gr.setRelationId(relationId);
				gr.setProduct(product);
				gr = productPriceDao.save(gr);
			}
			gr.setListPrice(Double.valueOf(listPrice));
			gr.setMemberPrice(Double.valueOf(memberPrice));
		} else {
			if (store == null)
				logger.info("Not Found Store id=[" + storeId + "]");
			if (product == null)
				logger.info("Not Found Product id=[" + productId + "]");
		}

		return true;
	}

	private boolean importUser(final Element element, final int sequence) {
		if (!element.getName().equals("User"))
			return false;

		String userId = element.attributeValue("id");

		User user = userDao.find(userId);
		if (user == null) {
			user = new User();
			user.setId(userId);
		}
		user.setFirstName(element.attributeValue("firstName"));
		user.setLastName(element.attributeValue("lastName"));
		user.setNickName(element.attributeValue("nickName"));
		user.setPassword(element.attributeValue("password"));
		String isServant = element.attributeValue("isServant");
		if (isServant != null && isServant.equals("Y"))
			user.setServant(true);
		else
			user.setServant(false);

		String isSupplier = element.attributeValue("isSupplier");
		if (isSupplier != null && isSupplier.equals("Y"))
			user.setSupplier(true);
		else
			user.setSupplier(false);

		user = userDao.save(user);

		String managedStoreId = element.attributeValue("managedStoreId");
		if (managedStoreId != null) {
			Store store = storeDao.find(managedStoreId);
			if (store != null) {
				user.setManagedStore(store);
				userDao.save(user);
			}
		}
		return true;
	}

	private boolean importUser2Store(final Element element, final int sequence) {
		if (!element.getName().equals("User2Store"))
			return false;

		String userId = element.attributeValue("userId");
		String relationName = element.attributeValue("relationName");
		String storeId = element.attributeValue("storeId");
		String comment = element.attributeValue("comment");

		Integer relationId = BusinessConstant.RelationID.valueOf(BusinessConstant.RelationID.class, relationName)
				.getId();

		User user = userDao.find(userId);
		Store store = storeDao.find(storeId);
		if (user != null && store != null) {
			GeneRelation gr = geneRelationDao.find(user.getSysId(), relationId, store.getSysId());
			if (gr == null) {
				gr = new GeneRelation();
				gr.setEntity(user);
				gr.setRelationId(relationId);
				gr.setEntity2(store);
				geneRelationDao.save(gr);
			}
		} else {
			if (store == null)
				logger.info("Not Found Store id=[" + storeId + "]");
			if (user == null)
				logger.info("Not Found User id=[" + userId + "]");
		}
		return true;
	}

	private boolean importUser2Product(final Element element, final int sequence) {
		if (!element.getName().equals("User2Product"))
			return false;

		String userId = element.attributeValue("userId");
		String relationName = element.attributeValue("relationName");
		String productId = element.attributeValue("productId");

		Integer relationId = BusinessConstant.RelationID.valueOf(BusinessConstant.RelationID.class, relationName)
				.getId();

		User user = userDao.find(userId);
		Product product = productDao.find(productId);
		if (user != null && product != null) {
			GeneRelation gr = geneRelationDao.find(user.getSysId(), relationId, product.getSysId());
			if (gr == null) {
				gr = new GeneRelation();
				gr.setEntity(user);
				gr.setRelationId(relationId);
				gr.setEntity2(product);
				geneRelationDao.save(gr);
			}
		} else {
			if (product == null)
				logger.info("Not Found Product id=[" + productId + "]");
			if (user == null)
				logger.info("Not Found User id=[" + userId + "]");
		}
		return true;
	}

	private boolean importUser2User(final Element element, final int sequence) {
		// <User2User emailAddr="demo931@500hao.com" relationType="classmate"
		// emailAddr2="demo@500hao.com"/>
		if (!element.getName().equals("User2User"))
			return false;

		String emailAddr = element.attributeValue("userId");
		String relationName = element.attributeValue("relationName");
		String emailAddrTo = element.attributeValue("userId2");
		String comment = element.attributeValue("comment");
		String status = element.attributeValue("status");

		//		try {
		//			Integer relationId = IConstants.RelationID.valueOf(IConstants.RelationID.class, relationName).getId();
		//
		//			User2User u2u = userDao.findUser2UserBy(emailAddr, relationId, null, emailAddrTo);
		//			if (u2u != null) {
		//				u2u.setShortDesc(comment);
		//				userDao.saveUser2User(u2u);
		//				// tagHelper.prepareTagOfUserRelations(comment, relationType,
		//				// u2u.getUser(), u2u.getUser2());
		//			} else {
		//				User user = userDao.findUserByUserId(emailAddr);
		//				User user2 = userDao.findUserByUserId(emailAddrTo);
		//				if (user != null && user2 != null) {
		//					u2u = new User2User();
		//					u2u.setShortDesc(comment);
		//					u2u.setUser(user);
		//					u2u.setRelationId(relationId);
		//					u2u.setUser2(user2);
		//					userDao.saveUser2User(u2u);
		//					// tagHelper.prepareTagOfUserRelations(comment, rt,
		//					// u2u.getUser(), u2u.getUser2());
		//				}
		//			}
		//		} catch (Exception e) {
		//			logger.info("Not Found relationType for relationName=[" + relationName + "]");
		//		}
		return true;
	}

	private boolean importSite2Site(final Element element, final int sequence) {
		// <Site2Site storeId="010.eetchina.com" relationType="parner"
		// homeUrl2="005.eetchina.com" status="approve" />
		if (!element.getName().equals("Site2Site"))
			return false;

		String storeId = element.attributeValue("storeId");
		String relationType = element.attributeValue("relationType");
		String homeUrl2 = element.attributeValue("homeUrl2");
		String comment = element.attributeValue("comment");
		String status = element.attributeValue("status");

		// Site2Site.RelationType rt =
		// Enum.valueOf(Site2Site.RelationType.class, relationType);
		// Site2Site.Status st = Enum.valueOf(Site2Site.Status.class, status);
		// if (rt != null && st != null) {
		// Site2Site u2u = siteDao.findSite2SiteBy(storeId, rt, homeUrl2);
		// if (u2u != null) {
		// u2u.setShortDesc(comment);
		// u2u.setStatus(st.getCode());
		// siteDao.saveSite2Site(u2u);
		// } else {
		// Store user = siteDao.findSiteBy(storeId);
		// Store g_user2 = siteDao.findSiteBy(homeUrl2);
		// if (user != null && g_user2 != null) {
		// u2u = new Site2Site();
		// u2u.setShortDesc(comment);
		// u2u.setStatus(st.getCode());
		// u2u.setSite(user);
		// u2u.setRelation(rt.getCode());
		// u2u.setSite2(g_user2);
		// siteDao.saveSite2Site(u2u);
		// }
		// }
		// }
		return true;
	}

	/**
	 * 
	 * @param element
	 *            e.g. <Content2Content productId="001.isbn"
	 *            relationType="iscrosssellof" contentId2="001.isbn"
	 *            status="approve" />
	 * @param sequence
	 * @return
	 */
	private boolean importContent2Content(final Element element, final int sequence) {

		if (!element.getName().equals("Content2Content"))
			return false;

		String productId = element.attributeValue("productId");
		String relationType = element.attributeValue("relationType");
		String contentId2 = element.attributeValue("contentId2");
		String comment = element.attributeValue("comment");
		String status = element.attributeValue("status");

		// Content2Content.RelationType rt =
		// Enum.valueOf(Content2Content.RelationType.class, relationType);
		// Content2Content.Status st =
		// Enum.valueOf(Content2Content.Status.class, status);
		// if (rt != null && st != null) {
		// Content2Content.RelationType[] relationTypes = { rt };
		// Content2Content c2c = contentDao.findContent2ContentBy(productId,
		// relationTypes, contentId2, st);
		// if (c2c != null) {
		// c2c.setShortDesc(comment);
		// c2c.setStatus(st.getCode());
		// contentDao.saveContent2Content(c2c);
		// } else {
		// Product coupon = contentDao.findContentBy(productId);
		// Product g_article2 = contentDao.findContentBy(contentId2);
		// if (coupon != null && g_article2 != null) {
		// c2c = new Content2Content();
		// c2c.setShortDesc(comment);
		// c2c.setStatus(st.getCode());
		// c2c.setContent(coupon);
		// c2c.setRelation(rt.getCode());
		// c2c.setContent2(g_article2);
		// contentDao.saveContent2Content(c2c);
		// }
		// }
		// }
		return true;
	}

	private boolean importCoupon2Content(final Element element, final int sequence) {

		if (!element.getName().equals("Coupon2Content"))
			return false;

		String couponId = element.attributeValue("couponId");
		String relationType = element.attributeValue("relationType");
		String productId = element.attributeValue("productId");
		String comment = element.attributeValue("comment");
		String status = element.attributeValue("status");

		// Coupon2Content.RelationType rt =
		// Enum.valueOf(Coupon2Content.RelationType.class, relationType);
		// Coupon2Content.Status st = Enum.valueOf(Coupon2Content.Status.class,
		// status);
		// if (rt != null && st != null) {
		// Coupon2Content.RelationType[] relationTypes = { rt };
		// Coupon2Content p2c = couponDao.findCoupon2ContentBy(couponId,
		// relationTypes, productId, st);
		// if (p2c != null) {
		// p2c.setShortDesc(comment);
		// p2c.setStatus(st.getCode());
		// couponDao.save(p2c);
		// } else {
		// Coupon coupon = couponDao.findCouponBy(couponId);
		// Product coupon = contentDao.findContentBy(productId);
		// if (coupon != null && coupon != null) {
		// p2c = new Coupon2Content();
		// p2c.setShortDesc(comment);
		// p2c.setStatus(st.getCode());
		// p2c.setCoupon(coupon);
		// p2c.setRelation(rt.getCode());
		// p2c.setContent(coupon);
		// couponDao.save(p2c);
		// }
		// }
		// }
		return true;
	}

	// private boolean importSiteFoodStore(final Element element, final int
	// sequence) {
	// if (!element.getName().equals("SiteFoodStore"))
	// return false;
	//
	// String storeId = element.attributeValue("storeId");
	// SiteFoodStore webSite = siteDao.findFoodStoreBy(storeId);
	// if (webSite == null) {
	// webSite = new SiteFoodStore();
	// webSite.setHomeUrl(storeId);
	// }
	// webSite.setName(element.attributeValue("name"));
	// webSite.setFullName(element.attributeValue("fullName"));
	// siteDao.save(webSite);
	// return true;
	// }

	// private boolean importUser2SiteOrder(final Element element, final int
	// sequence) {
	// // <User2SiteOrder orderId="001.orderfood" emailAddr="demo001@500hao.com"
	// // relationType="orderFood" storeId="001.foodstore.com"
	// discountAmount="108"
	// // status="approve">
	// // <User2SiteOrderItem productId="001.food" contentUnitPrice="18"
	// // contentQuantity="1"/>
	// // <User2SiteOrderItem productId="002.food" contentUnitPrice="28"
	// // contentQuantity="2"/>
	// // <User2SiteOrderItem productId="003.food" contentUnitPrice="38"
	// // contentQuantity="3"/>
	// // <User2SiteOrderItem productId="004.food" contentUnitPrice="48"
	// // contentQuantity="4"/>
	// // <User2SiteOrderItem productId="005.food" contentUnitPrice="58"
	// // contentQuantity="5"/>
	// // </User2SiteOrder>
	//
	// if (!element.getName().equals("User2SiteOrder"))
	// return false;
	//
	// String orderId = element.attributeValue("orderId");
	// String emailAddr = element.attributeValue("emailAddr");
	// String relationType = element.attributeValue("relationType");
	// String storeId = element.attributeValue("storeId");
	// String status = element.attributeValue("status");
	// User2Site.RelationType rt = Enum.valueOf(User2Site.RelationType.class,
	// relationType);
	// User2SiteOrder.Status st = Enum.valueOf(User2SiteOrder.Status.class,
	// status);
	// if (rt != null && st != null) {
	// User2SiteOrder u2u = userDao.findUser2SiteOrderBy(orderId);
	// if (u2u != null) {
	// u2u.setStatus(st.getCode());
	// u2u.setRelationType(rt.getCode());
	// u2u.setStatus(status);
	// userDao.saveUser2Site(u2u);
	// } else {
	// u2u = new User2SiteOrder();
	// User user = userDao.findUserByEmail(emailAddr);
	// Store store = siteDao.findSiteBy(storeId);
	// u2u.setOrderId(orderId);
	// u2u.setUser(user);
	// u2u.setRelationType(rt.getCode());
	// u2u.setStatus(st.getCode());
	// u2u.setSite(store);
	// u2u.setOrderItems(null);
	// if (user != null && store != null) {
	// u2u = (User2SiteOrder) userDao.saveUser2Site(u2u);
	// List<User2SiteOrderItem> orderItems =
	// prepareOrderItems(element.elements(), u2u);
	// u2u.setOrderItems(orderItems);
	// u2u = (User2SiteOrder) userDao.saveUser2Site(u2u);
	// }
	// }
	// }
	//
	// return true;
	// }
	//
	// private List<User2SiteOrderItem> prepareOrderItems(List elements,
	// User2SiteOrder order) {
	// List<User2SiteOrderItem> result = new ArrayList<User2SiteOrderItem>(0);
	// Iterator it = elements.iterator();
	// while (it.hasNext()) {
	// Element e = (Element) it.next();
	// if (!e.getName().equals("User2SiteOrderItem"))
	// continue;
	// // <User2SiteOrderItem productId="001.food" contentUnitPrice="18"
	// // contentQuantity="1"/>
	// String productId = e.attributeValue("productId");
	// String contentUnitPrice = e.attributeValue("contentUnitPrice");
	// String contentQuantity = e.attributeValue("contentQuantity");
	// Product coupon = contentDao.findContentBy(productId);
	// if (coupon != null) {
	// User2SiteOrderItem orderItem = new User2SiteOrderItem();
	// orderItem.setContent(coupon);
	// orderItem.setContentUnitPrice(Double.valueOf(contentUnitPrice));
	// orderItem.setContentQuantity(Double.valueOf(contentQuantity));
	// orderItem.setOrderHeader(order);
	// result.add(orderItem);
	// }
	// }
	// return result;
	// }

	private boolean importUser2Content(final Element element, final int sequence) {
		if (!element.getName().equals("User2Content"))
			return false;

		String userId = element.attributeValue("userId");
		String relationName = element.attributeValue("relationName");
		String productId = element.attributeValue("productId");
		String comment = element.attributeValue("comment");
		String status = element.attributeValue("status");

		//		try {
		//			Integer relationId = IConstants.RelationID.valueOf(IConstants.RelationID.class, relationName).getId();
		//
		//			User2Content u2c = userDao.findUser2ContentBy(userId, relationId, productId);
		//			if (u2c != null) {
		//				u2c.setShortDesc(comment);
		//				userDao.saveUser2Content(u2c);
		//			} else {
		//				User user = userDao.findUserByUserId(userId);
		//				Product product = contentDao.findContentByContentId(productId);
		//				if (user != null && product != null) {
		//					// 0.create User2Content
		//					u2c = new User2Content();
		//					u2c.setUser(user);
		//					u2c.setRelationId(relationId);
		//					u2c.setContent(product);
		//					u2c.setShortDesc(comment);
		//					userDao.saveUser2Content(u2c);
		//				}
		//			}
		//		} catch (Exception e) {
		//			logger.info("Not Found relationType for relationName=[" + relationName + "]");
		//		}

		return true;
	}

	// <User2Category emailAddr="demo001@500hao.com"
	// relationType="platinummember"
	// id="cn"/>
	private boolean importUser2Category(final Element element, final int sequence) {
		if (!element.getName().equals("User2Category"))
			return false;

		String userId = element.attributeValue("userId");
		String relationName = element.attributeValue("relationName");
		String categoryId = element.attributeValue("categoryId");

		Integer relationId = BusinessConstant.RelationID.valueOf(BusinessConstant.RelationID.class, relationName)
				.getId();

		User user = userDao.find(userId);
		Category category = categoryDao.find(categoryId);
		if (user != null && category != null) {
			GeneRelation gr = geneRelationDao.find(user.getSysId(), relationId, category.getSysId());
			if (gr == null) {
				gr = new GeneRelation();
				gr.setEntity(user);
				gr.setRelationId(relationId);
				gr.setEntity2(category);
				geneRelationDao.save(gr);
			}
		} else {
			if (user == null)
				logger.info("Not Found User id=[" + userId + "]");
			if (category == null)
				logger.info("Not Found Category id=[" + categoryId + "]");
		}

		return true;
	}

	private boolean importCoupon(final Element element, final int sequence) {
		if (!element.getName().equals("StoreCoupon"))
			return false;
		//<StoreCoupon id="cp00001" name="cp00001 Coupon Name" rank="999"  status="IS_APPROVE_SUCC" startDate="2007-10-10" endDate="2008-12-12" storeId="stid00001" />

		String couponId = element.attributeValue("id");
		String name = element.attributeValue("name");
		String desc = element.attributeValue("desc");
		String status = element.attributeValue("status");
		String bonusValue = element.attributeValue("bonusValue");
		
		Integer bonusValue1 = Integer.valueOf(bonusValue);
		Integer statusId = -1;
		if (status != null) {
			statusId = BusinessConstant.RelationID.valueOf(BusinessConstant.Status.class, status).getId();
		}

		String startDate = element.attributeValue("startDate");
		String endDate = element.attributeValue("endDate");

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date validStartDate1 = new Date();
		try {
			validStartDate1 = df.parse(startDate);
		} catch (ParseException e) {
		}
		Date validEndDate1 = new Date();
		try {
			validEndDate1 = df.parse(endDate);
		} catch (ParseException e) {
		}

		String storeId = element.attributeValue("storeId");
		Store store = storeDao.find(storeId);
		Coupon coupon = couponDao.findCoupon(couponId);

		if (store != null) {
			if (coupon == null) {
				coupon = new Coupon();
				coupon.setId(couponId);
			}
			coupon.setName(name);
			coupon.setShortDesc(desc);
			coupon.setStatus(statusId);
			coupon.setStartDate(validStartDate1.getTime());
			coupon.setEndDate(validEndDate1.getTime());
			coupon.setBonusValue(bonusValue1);
			coupon.setStore(store);
			couponDao.saveCoupon(coupon);
		}
		return true;
	}

	private boolean importCouponItem(final Element element, final int sequence) {
		if (!element.getName().equals("StoreCouponItem"))
			return false;
		//<StoreCouponItem id="cpi00001" name="cpi00001 Coupon Item Name" lotteryNumber0="2515263240" lotteryNumber1="2515263241"  status="IS_APPROVE_SUCC"  userId="demo@ungoo.com" />

		String couponItemId = element.attributeValue("id");
		String name = element.attributeValue("name");
		String lotteryNumber1 = element.attributeValue("lotteryNumber1");
		String lotteryNumber2 = element.attributeValue("lotteryNumber2");

		String couponId = element.attributeValue("couponId");
		String userId = element.attributeValue("userId");

		Coupon coupon = couponDao.findCoupon(couponId);
		User user = userDao.find(userId);
		CouponItem couponItem = couponDao.findCouponItem(couponItemId);

		if (coupon != null && user != null) {
			if (couponItem == null) {
				couponItem = new CouponItem();
				couponItem.setId(couponItemId);
			}
			couponItem.setLotteryNumber1(lotteryNumber1);
			couponItem.setLotteryNumber2(lotteryNumber2);
			couponItem.setCoupon(coupon);
			couponItem.setUser(user);
			couponDao.saveCouponItem(couponItem);
		}

		return true;
	}

	private boolean importStoreTransaction(final Element element, final int sequence) {
		if (!element.getName().equals("StoreTransaction"))
			return false;
		//<StoreCouponItem id="cpi00001" name="cpi00001 Coupon Item Name" lotteryNumber0="2515263240" lotteryNumber1="2515263241"  status="IS_APPROVE_SUCC"  userId="demo@ungoo.com" />

		String value = element.attributeValue("value");
		String shortDesc = element.attributeValue("shortDesc");
		String couponItemId = element.attributeValue("couponItemId");
		String storeId = element.attributeValue("storeId");
		String operatorUserId = element.attributeValue("operatorUserId");

		User operator = userDao.find(operatorUserId);
		Store store = storeDao.find(storeId);
		CouponItem couponItem = null;
		if (couponItemId != null) {
			couponItem = couponDao.findCouponItem(couponItemId);
		}
		if (store != null && operator != null) {
			StoreTransaction ltx = storeTransactionDao.findLatest(store.getSysId());
			int balance = 0;
			if (ltx != null) {
				balance = ltx.getBalance();
			}
			StoreTransaction result = new StoreTransaction();
			result.setValue(Integer.valueOf(value));
			result.setBalance(balance + Integer.valueOf(value));
			result.setShortDesc(shortDesc);
			result.setStore(store);
			result.setCouponItem(couponItem);
			result.setOperator(operator);
			storeTransactionDao.save(result);
		}

		return true;
	}

	private boolean importCategory2Category(final Element element, final int sequence) {
		if (!element.getName().equals("Category2Category"))
			return false;

		String categoryId = element.attributeValue("categoryId");
		String relationName = element.attributeValue("relationName");
		String categoryId2 = element.attributeValue("categoryId2").toLowerCase();
		String comment = element.attributeValue("comment");
		String status = element.attributeValue("status");
		Integer relationId = BusinessConstant.RelationID.valueOf(BusinessConstant.RelationID.class, relationName)
				.getId();
		Integer[] relationIds = { relationId };
		//		List<Category2Category> g2gs = categoryDao.getListCategory2CategoryBy(categoryId, relationIds, categoryId2,
		//				null, null, 0, 1);
		//		Category2Category g2g = null;
		//		if (g2gs != null && g2gs.size() > 0) {
		//			g2g = g2gs.get(0);
		//			g2g.setShortDesc(comment);
		//			categoryDao.saveCategory2Category(g2g);
		//		} else {
		//			Category category = categoryDao.findCategoryByCategoryId(categoryId);
		//			Category category2 = categoryDao.findCategoryByCategoryId(categoryId2);
		//			if (category != null && category != null) {
		//				g2g = new Category2Category();
		//				g2g.setCategory(category);
		//				g2g.setRelationId(relationId);
		//				g2g.setCategory2(category2);
		//				categoryDao.saveCategory2Category(g2g);
		//			} else if (category == null) {
		//				logger.info("Not Found Category for categoryId=[" + categoryId + "]");
		//			} else if (category2 == null) {
		//				logger.info("Not Found Category for categoryId2=[" + categoryId2 + "]");
		//			}
		//		}

		return true;
	}

}
